package com.huilian.iotbox.mqtt.server.base.service.impl;

import com.huilian.iotbox.mqtt.server.base.dao.DeviceDao;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.DeviceDto;
import com.huilian.iotbox.data.po.*;
import com.huilian.iotbox.data.vo.DeviceVo;
import com.huilian.iotbox.mqtt.server.base.service.*;
import com.huilian.iotbox.mqtt.server.base.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author 谢洛涛
 * @date 2021/3/31 12:05
 */
@Slf4j
@Service
public class DeviceServiceImpl implements DeviceService {

    @Resource
    private DeviceDao deviceDao;

    @Override
    public ServerResponse updateDeviceById(DeviceDto deviceDto) {
        return ServerResponse.createBySuccess(deviceDao.updateDeviceById(deviceDto));
    }

    @Override
    public DeviceVo findOneDeviceByDeviceNo(String deviceNo) {
        return deviceDao.findOneDeviceByDeviceNo(deviceNo);
    }

    @Override
    public Integer insert(Device device) {
        return deviceDao.insert(device);
    }

    @Override
    public void checkUploadAccountCode(DeviceDto deviceDto, Product product, DeviceVo deviceVo, Integer loginId) {
        if (loginId.compareTo(0) > 0) {
            if (!StringUtils.isEmpty(product)) {
                if ((StringUtils.isEmpty(deviceVo.getNextUploadAccountCode()) || StringUtils.isEmpty(deviceVo.getProductId()))) {
                    // 原nextUploadAccountCode为空或device表的productId为空就要更新nextUploadAccountCode字段
                    deviceDto.setNextUploadAccountCode(product.getDefaultUploadAccountCode());
                } else if (deviceVo.getProductId().compareTo(product.getId()) != 0) {
                    // 设备表的productId与实际上报不一致就要更新nextUploadAccountCode字段
                    deviceDto.setNextUploadAccountCode(product.getDefaultUploadAccountCode());
                }
            } else {
                // 有串口但没加入数据库的，默认1。虽然1不确定是否对，但是账目上报有做容错调整。如自增码错误，但金额和币数一致就会被命中线上投币、出币
                deviceDto.setNextUploadAccountCode(1);
            }
        }
    }

}
